package com.epam.DAO.JPA;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;

import com.epam.DAO.BillDAO;
import com.epam.entity.Bill;
import com.epam.entity.Client;
import com.epam.entity.Request;
import com.epam.entity.Status;

public class BillDAOJPA extends GenericDAOJPA<Bill> implements BillDAO {

	public BillDAOJPA() {
		super(Bill.class);
	}
		
	@Override
	public List<Bill> getBills(Status... status) {
		EntityManager em = getEntityManager();
		StringBuffer queryString = new StringBuffer(
				"SELECT b FROM Bill b WHERE b.status = ?1");
		for (int i = 2; i <= status.length; i++) {
			queryString.append(" OR r.status = ?" + i);
		}
		
		TypedQuery<Bill> query = em.createQuery(queryString.toString(),
				Bill.class);
		for (int i = 0; i < status.length; i++) {
			query.setParameter(i + 1, status[i]);
		}
		List<Bill> list = query.getResultList();
		em.close();
		return list;
	}

	@Override
	public List<Bill> getRequestBills(Request request) {
		EntityManager em = getEntityManager();
		TypedQuery<Bill> query = em.createQuery(
				"SELECT DISTINCT b FROM Bill b WHERE b.request = :request",
				Bill.class).setParameter("request", request);
		List<Bill> list = query.getResultList();
		em.close();
		return list;
	}

	@Override
	public List<Bill> getUserBills(Client client, Status... status) {
		// "SELECT * FROM rent.user u, rent.request r, rent.bill b" +
		// " WHERE u.user_id = r.user_id and r.REQUEST_ID = b.REQUEST_ID and b.bill_status = 'NOT PAYED' and u.user_id = ?1",
		
		EntityManager em = getEntityManager();
		StringBuffer queryString = new StringBuffer(
				"SELECT DISTINCT b FROM Bill b "
						+ "WHERE b.request.client = :client AND b.status = ?1");
		for (int i = 2; i <= status.length; i++) {
			queryString.append(" OR b.status = ?" + i);
		}
		TypedQuery<Bill> query = em.createQuery(queryString.toString(),
				Bill.class);
		query.setParameter("client", client);
		for (int i = 0; i < status.length; i++) {
			query.setParameter(i + 1, status[i]);
		}
		List<Bill> list = query.getResultList();
		em.close();
		return list;
	}

}
